'use strict';
// Copyright 2014 Blueant Inc. All Rights Reserved.

/**
 * @fileoverview 对手信息
 * @author sundbcn@gmail.com (sun debing)
 */

var async = require('async');
var _ = require('lodash');
var dataApi = require('../libs/dataApi');
var buildType = require('../consts/buildType');
var roleModel = require('../models/roleModel');
var unionGroupModel = require('../models/unionGroupModel');
var buildTypeUtil = require('../util/buildTypeUtil');
var constantUtil = require('../util/constantUtil');
var battleModel = require('../models/battleModel');
var pvpModel = require('../models/pvpModel.js');
var pvpService = require('../services/pvpService.js');

/**
 * 获取对手信息
 */
exports.getInfo = function (rival_player_manager, callback) {
    var rival_job_type = 0;
    var rival_lv = 0;
    var rival_name = '';
    var rival_gold = 0;
    var rival_cup = 0;
    var rival_food = 0;
    var rival_noble = 0;
    var rival_road_list = [];
    var rival_arrow_list = [];
    var rival_arrow_type_list = [];
    var rival_soldier_list = [];
    var rival_barrack_list = [];
    var rival_fight_power = 0;
    var rival_role_id = rival_player_manager.getRoleId();
    var harry_res;
    var union_model = null;

    async.waterfall([
            function (cb) {
                rival_player_manager.getModel(['role', 'battle', 'build', 'tech', 'soldier', 'accrued'], cb);
            },
            function (cb) {
                var union_id = rival_player_manager.role.union_id;
                if (union_id !== 0) {
                    unionGroupModel.getById(union_id, function (err, model) {
                        union_model = model;
                        cb();
                    });
                } else {
                    cb();
                }
            },
            function (cb) {
                var role_model = rival_player_manager.role;
                var battle_model = rival_player_manager.battle;
                var build_model = rival_player_manager.build;
                var tech_model = rival_player_manager.tech;
                var soldier_model = rival_player_manager.soldier;

                rival_job_type = role_model.getJob();
                rival_lv = role_model.getLv();
                rival_name = role_model.getName();
                rival_gold = role_model.getGold();
                rival_food = role_model.getFood();
                rival_cup = battle_model.getCup();
                rival_noble = battle_model.getNoble();
                rival_road_list = build_model.getRoadList();
                rival_fight_power = build_model.wall_soldier_power;

                // 获取箭塔列表
                var build_list = build_model.getDefBuildList();
                _.each(build_list, function (build) {
                    var build_type = build.getBuildType();
                    if (buildTypeUtil.isTower(build_type)) {
                        if (_.indexOf(rival_arrow_type_list, build.getBuildType()) == -1) {
                            rival_arrow_type_list.push(build.getBuildType());
                        }
                        rival_arrow_list.push(build.getCell());
                    } else if (build.getBuildType() == buildType.BARRACK) {
                        rival_barrack_list.push(build.getCell());
                    }
                });

                // 获取城墙兵种列表
                var wall_build = build_model.getBuildByType(buildType.WALL);
                var wall_soldier_list = wall_build.getSelectSoldier();
                var soldier_list = [];
                _.forEach(wall_soldier_list, function (batch_info) {
                    soldier_list = _.union(soldier_list, batch_info.sub_soldier_list);
                });
                rival_soldier_list = soldier_list;

                harry_res = pvpService.getHarryRes(role_model, build_model, tech_model, union_model);

                cb();
            }
        ],
        function (err) {
            if (!!err) {
                console.error(err);
            }
            callback(null, {
                role_id: rival_role_id,
                job_type: rival_job_type,
                gold: harry_res.gold,
                food: harry_res.food,
                cup: rival_cup,
                name: rival_name,
                noble: rival_noble,
                lv: rival_lv,
                road_list: rival_road_list,
                arrow_list: rival_arrow_list,
                arrow_type_list: rival_arrow_type_list,
                soldier_list: rival_soldier_list,
                barrack_list: rival_barrack_list,
                main_power: rival_fight_power
            });
        }
    );
};

var HARRY_LIST_LENGTH = 30;
/**
 * 随机生成掠夺对手ID
 */
exports.getRandomRivalRoleId = function (self_role_id, filter_role_id_list, callback) {
    var role_id_list = [];
    var rand_rival_role_id = 0;
    var noble = 0;
    filter_role_id_list.push(self_role_id);
    async.waterfall(
        [
            function (cb) {
                battleModel.getByRoleId(self_role_id, cb);
            },
            function (model, cb) {
                noble = model.getNoble();

                // 从同级官阶获取列表
                roleModel.getRoleByNobleListNotInProtect(noble, filter_role_id_list, HARRY_LIST_LENGTH, cb);
            },
            function (role_list, cb) {
                if (!!role_list && role_list.length > 0) {
                    _.forEach(role_list, function (role_info) {
                        role_id_list.push(role_info.role_id);
                    });
                }
                if (role_id_list.length < HARRY_LIST_LENGTH) {
                    // 从上下官阶获取列表(下2上1)
                    _getRoleIdListByNobleSection(self_role_id, noble, filter_role_id_list, role_id_list, cb);
                } else {
                    cb();
                }
            },
            function (cb) {
                if (role_id_list.length > 0) {
                    var rand_idx = _.random(0, role_id_list.length - 1);
                    rand_rival_role_id = role_id_list[rand_idx];
                }
                cb();
            }
        ],
        function (err) {
            if (!!err) {
                console.error(err);
            }
            callback(null, rand_rival_role_id);
        }
    );
};

/**
 * 从上下官阶获取列表(下2上1)
 */
var _getRoleIdListByNobleSection = function (role_id, noble, filter_role_id_list, role_id_list, callback) {
    var lower_noble = noble - 1;
    var upper_noble = noble + 1;
    var is_end = false;
    var rand_rival_role_id;
    var role_noble_count = dataApi.pvp_position.length();
    async.whilst(
        function () {
            return (lower_noble >= 1 || upper_noble <= role_noble_count) && role_id_list.length < HARRY_LIST_LENGTH;
        },
        function (cb) {
            var need_num = HARRY_LIST_LENGTH - role_id_list.length;
            var lower_need = need_num * 2 / 3;
            var upper_need = need_num - lower_need;
            roleModel.getRoleByNobleListNotInProtect(lower_noble, filter_role_id_list, need_num, function (err, lower_role_list) {
                roleModel.getRoleByNobleListNotInProtect(upper_noble, filter_role_id_list, need_num, function (err, upper_role_list) {
                    if (!lower_role_list) {
                        lower_role_list = [];
                    }
                    if (!upper_role_list) {
                        upper_role_list = [];
                    }
                    if (lower_role_list.length < lower_need) {
                        // 下级不足：下取所有，上按需取
                        _.forEach(lower_role_list, function (role_info) {
                            role_id_list.push(role_info.role_id);
                        });

                        upper_need = HARRY_LIST_LENGTH - role_id_list.length;
                        upper_role_list = _.slice(upper_role_list, 0, upper_need);
                        _.forEach(upper_role_list, function (role_info) {
                            role_id_list.push(role_info.role_id);
                        });
                    } else {
                        // 下充足
                        if (upper_role_list.length < upper_need) {
                            // 上不足(下足)：上取所有
                            _.forEach(upper_role_list, function (role_info) {
                                role_id_list.push(role_info.role_id);
                            });
                        } else {
                            // 上下充足
                            upper_role_list = _.slice(upper_role_list, 0, upper_need);
                        }

                        lower_need = HARRY_LIST_LENGTH - role_id_list.length;
                        lower_role_list = _.slice(lower_role_list, 0, lower_need);
                        _.forEach(lower_role_list, function (role_info) {
                            role_id_list.push(role_info.role_id);
                        });
                    }

                    lower_noble -= 1;
                    upper_noble += 1;
                    cb();
                });
            });
        },
        function (err) {
            callback(err);
        }
    );
};
